package com.store.practice.common.utils;



import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil {
    private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtil.class);
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    //根据claim生成token
    private String generateToken(Map<String,Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }
    //从token中获取过期时间
    private Date getExpirarionFromToken(String token){
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }
    //验证token是否过期
    private boolean isTokenExpired(String token){
        Date expiredDate = getExpirarionFromToken(token);
        return expiredDate.before(new Date());
    }
    //根据token获取username
    public String getUsernameFromToken(String token){
        String username;
        try{
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        }catch(Exception e){
            username = null;
        }
        return username;
    }
    //生成token到期日期
    private Date generateExpirationDate(){
        return new Date(System.currentTimeMillis() + expiration * 1000);
        }
    //从token中获取jwt的负载claims
    private Claims getClaimsFromToken(String token){
        Claims claims = null;
        try{
            claims = Jwts.parser()
                        .setSigningKey(secret)
                        .parseClaimsJws(token)
                        .getBody();
        }catch(Exception e){
            logger.info("验证码格式错误{}",token);
        }
        return claims;
    }
    //根据用户信息生成token
    public String generateToken(UserDetails userDetails){
        Map<String,Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME,userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claims);
    }
    //判断token能否被刷新
    public boolean isBeRefreshed(String token){
        return !isTokenExpired(token);
    }
    //刷新token
    public String refreshToken(String token){
        Claims claims = getClaimsFromToken(token);
        claims.setExpiration(new Date());
        return generateToken(claims);
    }
    //判断token是否有效
    public boolean validateToken(UserDetails userDetails,String token){
        String username = getUsernameFromToken(token);
        return username.equals(userDetails.getUsername()) & !isTokenExpired(token);
    }
}
